package org.dg.iag.util;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Hashtable;

import org.dg.iag.dao.UserDAO;
import org.dg.iag.entity.User;
import org.restlet.Request;
import org.restlet.data.Cookie;
import org.restlet.util.Series;

public class LoginUtil {
	
		private static Hashtable<String, String> sessions	= new Hashtable<String, String>();
		
		
		public static boolean checkLogin ( Request req ) {
			
			//UGLY hack for when the application itself needs to gets access to the database;
			if ( req == null)
				return true;
			
			Series<Cookie> cookies = req.getCookies();
			if ( cookies != null) {
				String username		= cookies.getValues(ApplicationConstants.COOKIE_USERNAME);
				String sessionid	= cookies.getValues(ApplicationConstants.COOKIE_SESSIONID);
				
				if ( username != null && username.length() > 0 &&  
					sessionid != null && sessionid.length() > 0 )
					return checkLogin(username, sessionid);
			}
			return false;
		}
		
		public static boolean checkLogin (String username, String sessionId) {
			if (username == null || sessionId == null)
				return false;
			
			String serverSessionId	= sessions.get(username);
			if (sessionId.equals(serverSessionId) )
				return true;
			
			return false;
		}
		
		/**
		 * 
		 * @param username
		 * @param password
		 * @return the generated session id if login is successful or null otherwise
		 */
		public static String login(String username, String password) {
			
			if (username != null && password != null ) {
				UserDAO udao	= new UserDAO();
				User u			= udao.getUser(username);
				if ( password.equals(u.getMd5Password()) ) {
					String sessionId	= getMD5(username+":"+password+":"+System.currentTimeMillis() );
					sessions.put(username, sessionId);
					return sessionId;
				}
			}
			return null;
		}
		
		public static void logout(String username) {
			if ( username != null ) {
				sessions.remove(username);
			}
		}

		public static String getMD5(String input) {
			try {
				MessageDigest md 		= MessageDigest.getInstance("MD5");
				byte[] messageDigest 	= md.digest(input.getBytes());
				BigInteger number 		= new BigInteger(1, messageDigest);
				String md5 		= number.toString(16);
				while (md5.length() < 32) {
					md5 = "0" + md5;
				}
				return md5;
			}
			catch (NoSuchAlgorithmException e) {
				throw new RuntimeException(e);
			}
		}

}
